<?php
Class C_users extends Cemvc_Control_Base
{
  private $db;
  private $user;

  public function __construct()
  {
    parent::__construct();
    $this->db = new M_qin_users();
    /* $this->db->SetDbCodeNames("utf8"); */

    if(isset($_REQUEST['userid']) && $_REQUEST['userid'])
      {
	$user = $this->db->get($_REQUEST['userid']);
	$region = new M_qin_region();
	$user['region'] = $user["region_code"] ? $region->get_full_name($user['region_code']) : "";
	$user['gender_str'] = $user['gender'] == MALE ? '男' : '女';
	$user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	$this->view->assign("user", $user);
	$this->user = $user;

	if (isset($_SESSION["id"]) && 
	    ($_SESSION["id"] == $user["creator"] ||	/* I create the user */
	     $_SESSION["id"] == $user["id"] ||	/* I am the user */
	     ($_SESSION["creator"] > 0 && $_SESSION["creator"] == $user["creator"]))) /* we were created with a same user */
	  {
	    $this->view->assign("authorized", 1);
	  }
      }

    if ($_POST)
      $this->view->assign("post", $_POST);

    $this->view->assign("male", MALE);
    $this->view->assign("female", FEMALE);
    $this->view->assign("open", M_Options::get_open_state());
    $this->view->assign("default_user", DEFAULT_USER_IN_HOME);
  }

  /* insert a user record into users table */
  public function register()
  {
    $region = new M_qin_region();
    $provinces = $region->getProvinceList();
    $this->assign("provinces", M_Tools::make_options($provinces));

    if($_POST)
      {
	$user = '';
	if (isset($_POST["username"]) && $_POST["username"])
	  {
	    $user = $this->db->get_user_with_username($_POST["username"]);
	    if ($user && $user["id"])
	      $this->view->assign("error", "你要注册的用户名已存在。");
	  }

	if(!$user || !isset($user["id"]))
	  { 
	    $add = $this->db->add($_POST);

	    /* register success */
	    if (isset($add["id"]) && $add["id"]>0)
	      {
		$_SESSION["id"] = $add["id"];
		$_SESSION["qq_open_id"] = $add["qq_open_id"];
		$_SESSION["realname"] = $add["realname"];
		$_SESSION["gender"] = $add["gender"];
		$_SESSION["region_code"] = $add["region_code"];
		$_SESSION["day_of_birth"] = $add["day_of_birth"];
		$_SESSION["figureurl"] = $add["figureurl"];
		$_SESSION["creator"] = $add["creator"];
		$this->setRole(ROLE_MEMBER);

		$this->redirect("family/manage");
		return;
	      }
	    else
	      $this->view->assign("error", "注册失败，请稍后重试。");
	  }
	/* $this->view->assign("post", $_POST); */
	$region = new M_qin_region();
	$options = $region->get_selected_options($_POST["region_code"]);
	$this->view->assign("provinces", $options["provinces"]);
	$this->view->assign("cities", $options["cities"]);
	$this->view->assign("towns", $options["towns"]);

      }
    /* $this->assign("openid", isset($_SESSION["openid"]) ? $_SESSION["openid"] : ''); */
    $this->display();
  }

  public function login()
  {
    if (isset($_REQUEST["msg"]) && !empty($_REQUEST["msg"]))
	$this->view->assign('msg', $_REQUEST['msg']);
    if (isset($_REQUEST["username"]) && !empty($_REQUEST["username"]) &&
	isset($_REQUEST["password"]) && !empty($_REQUEST["password"]) )
      {

	$arr = $this->db->get_user($_REQUEST["username"], $_REQUEST["password"]);
	if ($arr && isset($arr['id']))
	  {
	    $this->setRole(ROLE_MEMBER);
	    $_SESSION["id"] = $arr["id"];
	    $_SESSION["realname"] = $arr["realname"];
	    $_SESSION["gender"] = $arr["gender"];
	    $_SESSION["region_code"] = $arr["region_code"];
	    $_SESSION["day_of_birth"] = $arr["day_of_birth"];
	    $_SESSION["figureurl"] = $arr["figureurl"];
	    $_SESSION["creator"] = $arr["creator"];

	    $this->redirect("family/manage");
	    return;
	  }
	else
	  {
	    /* $this->view->assign("username", $_REQUEST["username"]); */
	    $this->view->assign("error", "用户名不存在或密码不匹配，请重新输入。");
	    $this->view->assign("post", $_POST);
	  }
      }

    $this->display();
  }

  public function register_complete()
  {
    $this->display();
  }

  public function add_person()
  {
    if (!isset($_SESSION["id"]) || empty($_SESSION["id"]))
      {
	$this->redirect("users/login");
	die();
      }
    $region = new M_qin_region();
    $provinces = $region->getProvinceList();
    $this->view->assign("provinces", M_Tools::make_options($provinces));
    $this->view->assign("creator", $_SESSION["id"]);
    $this->display();
  }

  public function insert_person()
  {
    if (!isset($_SESSION["id"]) || empty($_SESSION["id"]))
      {
	$this->redirect("users/login");
	die();
      }
    $user = $this->db->add($_POST);
    
    /* $user = $this->db->get_last_create($_SESSION["id"]); */
    $this->view->assign("user", $user);
    $this->display();
  }

  /* show user information, include user's photos, events, birthday to death */
  public function home()
  {
    $user_id = isset($_REQUEST['userid']) ? $_REQUEST["userid"] : ( isset($_SESSION["id"]) ? $_SESSION["id"] : '');
    if (!$user_id)
      {
	$this->redirect("users/login");
	return;
      }
    
    $user = $this->db->get($user_id);
    if (!$user)
      die("user not exists with id ".$user_id);

    $region = new M_qin_region();
    $user['region'] = $user['region_code'] ? $region->get_full_name($user['region_code']) : "";
    $user['gender_str'] = $user['gender'] == MALE ? '男' : '女';
    $user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
    $this->view->assign("user", $user);

    /* get family data */
    $db = new M_qin_relation();
    $this->view->assign("mothers", $db->get_mothers($user_id, RESOURCE_STATE_INIT));
    $this->view->assign("fathers", $db->get_fathers($user_id, RESOURCE_STATE_INIT));
    $this->view->assign("mates", $db->get_mates($user_id, RESOURCE_STATE_INIT));
    $this->view->assign("sons", $db->get_sons($user_id, RESOURCE_STATE_INIT));
    $event = new M_qin_events();
    $events = $event->get_events($user_id);
    $this->view->assign("events", $events);

    /* add visit record to visits table */
    $visit = new M_qin_visits();
    $visit->add_visit($user_id, isset($_SESSION["id"]) ? $_SESSION["id"] : 0);
    $views = $visit->get_visit($user_id);
    $this->view->assign("views", $views);

    $this->display();
  }

  public function album()
  {
    $user_id = isset($_REQUEST['userid']) ? $_REQUEST["userid"] : ( isset($_SESSION["id"]) ? $_SESSION["id"] : '');
    if (!$user_id)
      {
	$this->redirect("users/login");
	return;
      }
    if (isset($_SESSION["id"]) && 
	($_SESSION["id"] == $this->user["creator"] ||	/* I create the user */
	 $_SESSION["id"] == $this->user["id"] ||	/* I am the user */
	 ($_SESSION["creator"] > 0 && $_SESSION["creator"] == $user["creator"]))) /* we were created with a same user */
      {
	$this->view->assign("authorized", 1);
      }

    $album_tbl = new M_qin_album();
    $album = $album_tbl->get_album($user_id);
    /* var_dump($album); */
    $this->view->assign("album", $album);
    $this->display();
  }
  public function add_event()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to show.");
    
    $this->view->assign("user", $this->db->get($_REQUEST['userid']));
    $this->display();
  }
  public function insert_event()
  {
    $user = $this->db->get($_POST["user_id"]);
    $links = new M_Links();
    $linked_event = $links->add_links($_POST["event"], $user["realname"]);
    $event = new M_qin_events();
    $data = array("user_id" => $_POST["user_id"], "date"=> $_POST["date"], "event"=> $linked_event);
    if (isset($_SESSION["openid"]) && $_SESSION["openid"] && $_SESSION["oauth"] == 'pengyou')
      {
	$res = M_QQ::word_filter($_SESSION["openid"], $_SESSION["openkey"], 
				 $linked_event, rand(1,100000), $_SESSION["pf"]);

	if (!$res["ret"] && $res["is_dirty"])
	  $data["event"] =  $res["msg"];
	$e = $event->add($data);
      }
    else
      {
	$e = $event->add($data);
      }

    $this->redirect("users/insert_event_complete?userid=".$_REQUEST["user_id"]);
  }
  public function edit_event()
  {
    if (!isset($_REQUEST["eventid"]) || empty($_REQUEST["eventid"]))
      die("You must specified an event id to edit.");

    $db = new M_qin_events();
    $event = $db->get($_REQUEST["eventid"]);
    $user = $this->db->get($event["user_id"]);
    if ($_POST)
      {

	$links = new M_Links();
	$event = $links->add_links($_POST["event"], $user["realname"]);
	/* $event = $_POST["event"]; */

	/* add words filter */
	if (isset($_SESSION["openid"]) && $_SESSION["openid"])
	  {
	    $res = M_QQ::word_filter($_SESSION["openid"], $_SESSION["openkey"], 
				     $event, rand(1,100000), $_SESSION["pf"]);
	    if (!$res["ret"] && $res["is_dirty"])
	      $event =  $res["msg"];
	  }
	/* end words filter */

	$event = $db->edit($_POST["eventid"], array("date"=>$_POST["date"],
						    "event"=>$event));
	$this->redirect("users/update_event_complete?userid=".$event["user_id"]);
	return;
      }
    $this->view->assign("user", $user);
    $this->view->assign("event", $event);
    $this->display();
  }
  public function delete_event()
  {
    if (!isset($_REQUEST["eventid"]) || empty($_REQUEST["eventid"]))
      die("You must specified an event id to edit.");
    $db = new M_qin_events();
    $event = $db->delete($_REQUEST["eventid"]);

    $this->redirect("users/delete_event_complete?eventid=".$_REQUEST["eventid"]."&userid=".$event["user_id"]);
  }
  public function update_event_complete()
  {
    $this->view->assign("user", $this->db->get($_REQUEST["userid"]));
    $this->display();
  }
  public function delete_event_complete()
  {
    $this->view->assign("eventid", $_REQUEST["eventid"]);
    $this->display();
  }
  public function insert_event_complete()
  {
    $this->view->assign("userid", $_REQUEST["userid"]);
    $this->display();
  }
  public function event_history()
  {
    if (!isset($_REQUEST["eventid"]) || empty($_REQUEST["eventid"]))
      die("You must specified an event id to edit.");

    $history = new M_qin_history();
    $res = $history->get_history_with_content(CONTENT_TYPE_EVENT, $_REQUEST["eventid"]);
    $this->assign("page", $history->showPages());

    $event = new M_qin_events();
    $e = $event->get($_REQUEST["eventid"]);
    $this->view->assign("user", $this->db->get($e["user_id"]));    
    $event_history = array();
    foreach($res as $item)
      {
	$item["content"] = unserialize(base64_decode($item["content"]));
	$event_history[] = $item;
      }

    $this->view->assign("history", $event_history);
    $this->display();
    
  }
  public function photo_history()
  {
    if (!isset($_REQUEST["photoid"]) || empty($_REQUEST["photoid"]))
      die("You must specified an photo id to edit.");

    $history = new M_qin_history();
    $res = $history->get_history_with_content(CONTENT_TYPE_PHOTO, $_REQUEST["photoid"]);
    $this->assign("page", $history->showPages());
    $event_history = array();
    foreach($res as $item)
      {
	$item["content"] = unserialize(base64_decode($item["content"]));
	/* $item["content"]['region'] = $region->get_full_name($item["content"]['region_code']); */
	$event_history[] = $item;
      }

    $album = new M_qin_album();
    $e = $album->get($_REQUEST["photoid"]);
    $this->view->assign("user", $this->db->get($e["user_id"]));

    $this->view->assign("history", $event_history);
    $this->display();
    
  }

  public function photo_restore()
  {
    if (!isset($_REQUEST["photoid"]) || empty($_REQUEST["photoid"]))
      die("You must specified an photo id to edit.");
    if (!isset($_REQUEST["historyid"]) || empty($_REQUEST["historyid"]))
      die("You must specified an history id to restore.");
   
    $album = new M_qin_album();
    $e = $album->restore($_REQUEST["photoid"], $_REQUEST["historyid"]);
    $this->redirect("users/photo_restore_complete?historyid=".$_REQUEST["historyid"]."&userid=".$e["user_id"]);
  }
  public function photo_restore_complete()
  {
    $this->view->assign("historyid", $_REQUEST["historyid"]);
    $this->display();    
  }
  public function delete_photo()
  {
    if (!isset($_REQUEST["photoid"]) || empty($_REQUEST["photoid"]))
      die("You must specified an photo id to edit.");
   
    $album = new M_qin_album();
    $e = $album->delete($_REQUEST["photoid"]);
    $this->redirect("users/photo_delete_complete?photoid=".$_REQUEST["photoid"]."&userid=".$e["user_id"]);
  }
  public function photo_delete_complete()
  {
    $this->view->assign("photoid", $_REQUEST["photoid"]);
    $this->display();    
  }
  public function event_restore()
  {
    if (!isset($_REQUEST["eventid"]) || empty($_REQUEST["eventid"]))
      die("You must specified an event id to edit.");
    if (!isset($_REQUEST["historyid"]) || empty($_REQUEST["historyid"]))
      die("You must specified an history id to restore.");
   
    $event = new M_qin_events();
    $e = $event->restore($_REQUEST["eventid"], $_REQUEST["historyid"]);
    $this->redirect("users/event_restore_complete?historyid=".$_REQUEST["historyid"]."&userid=".$e["user_id"]);
  }
  public function event_restore_complete()
  {
    $this->view->assign("historyid", $_REQUEST["historyid"]);
    $this->display();
  }
  public function add_photo_through_qq()
  {
	  $this->display();
  }
  public function add_photo()
  { 
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to show.");
    
    $this->view->assign("upload_id", md5(date("gis").rand(1,1000)));
    $this->view->assign("user", $this->db->get($_REQUEST['userid']));
    $this->display();
  }
  Public function insert_photo_url()
  {
    if (!isset($_REQUEST['user_id']) || empty($_REQUEST['user_id']))
      die("You must specify a user id to show.");
    if (!isset($_REQUEST['photos']) || empty($_REQUEST['photos']))
      die("You must specify some photos to insert.");

    $photos = explode(";", $_REQUEST["photos"]);
    $album = new M_qin_album();
    $failed = 0;
    foreach($photos as $photo)
    {
	    $p = $album->add(array("user_id"=>$_REQUEST["user_id"], "photo"=>$photo, "memo"=>""));
	    if (!isset($p["id"]) || !$p["id"])
	      $failed = 1;
    }
    
    die(json_encode(array("resp_id"=>$failed, "resp_str"=>"成功添加图片！")));
  }
  public function insert_photo()
  {
    /* var_dump($_REQUEST);  */
    if (!isset($_REQUEST['user_id']) || empty($_REQUEST['user_id']))
      die("You must specify a user id to show.");
    if (!isset($_FILES["photo"]["tmp_name"]) || !file_exists($_FILES["photo"]["tmp_name"]))
      die("the photo you upload is not exists.");

    /* create the photo directory if not exists */
    $rel_dir = ALBUM_DIR."/".date('Ymd');
    $abs_dir = WEB_ROOT . $rel_dir;
    /* print "abs dir: $abs_dir<br/>"; */
    if (!is_dir($abs_dir))
      mkdir($abs_dir, 0777);

    /* move the upload photo to reposity */
    $new_name = md5($_FILES["photo"]["tmp_name"]).".".strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION));
    /* rename($_FILES["photo"]["tmp_name"], $abs_dir."/".$new_name); */

    /* if photo is large, I will resize it(resuce the size) to save the bandwith and storage */
    if ($_FILES["photo"]["size"] >= SIZE_EXLARGE)
      $scale = SCALE_EXLARGE;
    else if ($_FILES["photo"]["size"] >= SIZE_LARGE)
      $scale = SCALE_LARGE;
    else if ($_FILES["photo"]["size"] >= SIZE_MEDIUM)
      $scale = SCALE_MEDIUM;
    else //if ($_FILES["photo"]["size"] >= SIZE_SMALL)
      $scale = SCALE_SMALL;

    $abs_new_file = $abs_dir."/".$new_name;
    $thumb_name = md5($_FILES["photo"]["tmp_name"]).".thumb.".strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION));
    $abs_thumb_file = $abs_dir."/".$thumb_name;

    $cmd = CONVERT_PROGRAM." -resize ${scale}x${scale} ".$_FILES["photo"]["tmp_name"]." ".$abs_new_file.";";
    $cmd .= CONVERT_PROGRAM." -resize x".PHOTO_THUMB_HEIGHT." ${abs_new_file} ${abs_thumb_file}";
    $str = exec($cmd, $res, $rc);

    $para = $_REQUEST;
    if (file_exists($abs_new_file))
    {
	    $para["photo"] = $rel_dir."/".$new_name;
	    $para["thumb"] = $rel_dir."/".$thumb_name;
	    $album = new M_qin_album();
	    $p = $album->add($para);
	    $succ = isset($p["id"]) && $p["id"] ? 0 : 1;
    }
    else
	    $succ = 1;
    $this->view->assign("userid", $_REQUEST["user_id"]);
    $this->redirect("users/insert_photo_complete?userid=".$_REQUEST["user_id"]."&success=".$succ);
  }
  public function insert_photo_complete()
  {
	  if (!isset($_REQUEST['userid']) || !isset($_REQUEST["success"]))
		  die("user id and insert state must be specified");

	  $this->view->assign("success", $_REQUEST["success"]);
	  $this->display();
  }
  public function add_figure()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $user = $this->db->get($_REQUEST['userid']);

    $album_tbl = new M_qin_album();
    $album = $album_tbl->get_album($user['id']);
    /* var_dump($album); */
    $this->view->assign("album", $album);
    $this->view->assign("userid", $user["id"]);
    $this->view->assign("realname", $user["realname"]);
    $this->view->assign("upload_id", md5(date("gis").rand(1,1000)));
    $this->view->assign("upload_max_filesize", M_Tools::return_bytes(ini_get('upload_max_filesize')));
    $this->display();
  }

  /* return upload information of the big photo */
  public function get_upload()
  {
    if (!isset($_REQUEST['upload_id']) || empty($_REQUEST['upload_id']))
      die("You must specify a upload id to monitor.");

    $upload = apc_fetch("upload_".$_REQUEST['upload_id']);

    die(json_encode($upload));
  }
  public function insert($array)
  {
    if(is_array($array))
      {
	$data["qq_open_id"]=isset($array["qq_open_id"]) ? $array["qq_open_id"] : '';
	$data["realname"]=$array['realname'];
	$data["gender"]=$array['gender'];
	$data["region_code"]=$array['region_code'];
	$data["day_of_birth"]=$array['day_of_birth'];
	//$data["figureurl"]=$array['figureurl'] ? $array['figureurl'] : "";
	$data["creator"]=isset($array['creator']) ? $array['creator'] : '';
	$this->db->insert($data);
      }
    else
      die("You must post the data to insert method.");

  }

  public function baseinfo_history()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $history = new M_qin_history();
    $res = $history->get_history_with_content(CONTENT_TYPE_USER, $_REQUEST["userid"]);
    $this->assign("page", $history->showPages());
    
    $base_history = array();
    $region = new M_qin_region();
    foreach($res as $item)
      {
	$item["content"] = unserialize(base64_decode($item["content"]));
	$item["content"]['region'] = $item["content"]['region_code'] ? $region->get_full_name($item["content"]['region_code']) : "";
	$base_history[] = $item;
      }

    $this->view->assign("history", $base_history);
    $this->display();
  }
  public function baseinfo_restore()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");
    if (!isset($_REQUEST['historyid']) || empty($_REQUEST['historyid']))
      die("You must specify a history id to restore.");

    $history = new M_qin_history();
    $res = $history->get($_REQUEST["historyid"]);
    
    $array = unserialize(base64_decode($res["content"]));
    $this->db->edit($_REQUEST["userid"], $array);
    $this->view->assign("historyid", $_REQUEST["historyid"]);

    $this->display();
  }
  public function contribution()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to see.");

    $history = new M_qin_history();
    $res = $history->get_history_with_author($_REQUEST["userid"]);
    $this->assign("page", $history->showPages());
    
    $items = array();
    $region = new M_qin_region();
    foreach($res as $item)
      {
	$item["content"] = unserialize(base64_decode($item["content"]));
	$items[] = $item;
      }

    $this->view->assign("history", $items);
    $this->display();
  }
  public function show_events()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to see.");

    $event = new M_qin_events();
    $events = $event->get_events($_REQUEST["userid"], null);
    $this->view->assign("events", $events);

    $this->display();    
  }
  public function edit_album()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $album_tbl = new M_qin_album();
    $album = $album_tbl->get_album($_REQUEST["userid"], null);
    $this->view->assign("album", $album);
    $this->display();    
  }
  public function edit_photo()
  {
    if (!isset($_REQUEST['photoid']) || empty($_REQUEST['photoid']))
      die("You must specify a photo id to edit.");

    $album_tbl = new M_qin_album();
    $photo = $album_tbl->get($_REQUEST['photoid']);
    if ($_POST)
      {
	$photo = $album_tbl->edit($_REQUEST['photoid'], $_POST);
	$this->redirect("users/update_photo_complete?userid=".$photo["user_id"]."&photoid=".$_REQUEST["photoid"]);
	return;
      }

    $this->view->assign("user", $this->db->get($photo["user_id"]));
    $photo = $album_tbl->get($_REQUEST["photoid"]);
    $this->view->assign("photo", $photo);
    $this->display();        
  }
  
  public function update_photo_complete()
  {
    if (!isset($_REQUEST['photoid']) || empty($_REQUEST['photoid']))
      die("You must specify a photo id to edit.");

    $this->view->assign("photoid", $_REQUEST["photoid"]);
    $this->display();    
  }
  public function edit_entry()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $user_id = $_REQUEST['userid'];
    $user = $this->db->get($user_id);
    if (isset($_SESSION["id"]) && 
	($_SESSION["id"] == $user["creator"] ||	/* I create the user */
	 $_SESSION["id"] == $user["id"] ||	/* I am the user */
	 ($_SESSION["creator"] > 0 && $_SESSION["creator"] == $user["creator"]))) /* we were created with a same user */
      {
	$this->view->assign("authorized", 1);
      }

    /* get family data */
    $db = new M_qin_relation();
    $this->view->assign("mothers", $db->get_mothers($user_id));
    $this->view->assign("fathers", $db->get_fathers($user_id));
    $this->view->assign("mates", $db->get_mates($user_id));
    $this->view->assign("sons", $db->get_sons($user_id));

    $this->display();
  }
  public function edit()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $table = new M_qin_users();
    $user = $table->get($_REQUEST['userid']);
    M_Tools::print_r($user);

    $region = new M_qin_region();
    $options = $region->get_selected_options($user["region_code"]);
    $this->view->assign("provinces", $options["provinces"]);
    $this->view->assign("cities", $options["cities"]);
    $this->view->assign("towns", $options["towns"]);

    $this->view->assign("male", MALE);
    $this->view->assign("female", FEMALE);
    /* $this->view->assign("user", $user); */
    $this->display();
  }
  public function update()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $table = new M_qin_users();
    $user = $table->edit($_REQUEST['userid'],
			 array("region_code"=>addslashes($_REQUEST["region_code"]),
			       "gender"=>addslashes($_REQUEST["gender"]),
			       "first_name"=>addslashes($_REQUEST["first_name"]),
			       "name"=>addslashes($_REQUEST["name"]),
			       "realname" => addslashes($_REQUEST["first_name"].$_REQUEST["name"]),
			       "symbol"=>addslashes($_REQUEST["symbol"]),
			       "title"=>addslashes($_REQUEST["title"]),
			       "day_of_birth"=>addslashes($_REQUEST["day_of_birth"]),
			       "open"=>addslashes($_REQUEST["open"]),
			       ));
    $this->view->assign("user", $this->db->get($_REQUEST['userid']));
    $this->display();
    
  }
  /* 编辑头像 */
  public function edit_figure1()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");
    
    $this->display();
  }
  public function edit_figure()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    if (isset($_REQUEST["photo"]) && !empty($_REQUEST["photo"]))
      {
	$this->view->assign("photo", $_REQUEST["photo"]);
      }
    /* DO NOT RECEIVE UPLOAD IMAGE FOR FIGURE, ONLY ACCEPT PHOTO FROM ALBUM */
    /* else if (isset($_FILES["photo"]["tmp_name"]) && file_exists($_FILES["photo"]["tmp_name"])) */
    /*   { */
    /* 	$new = md5($_FILES["photo"]["tmp_name"]).".".strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION)); */
    /* 	$rel = TMP_DIR."/".$new; */
    /* 	rename($_FILES["photo"]["tmp_name"], WEB_ROOT.$rel); */

    /* 	/\* if photo is large, I will resize it(resuce the size) to save the bandwith and storage *\/ */
    /* 	if ($_FILES["photo"]["size"] >= SIZE_EXLARGE) */
    /* 	  $scale = SCALE_EXLARGE; */
    /* 	else if ($_FILES["photo"]["size"] >= SIZE_LARGE) */
    /* 	  $scale = SCALE_LARGE; */
    /* 	else if ($_FILES["photo"]["size"] >= SIZE_MEDIUM) */
    /* 	  $scale = SCALE_MEDIUM; */
    /* 	else //if ($_FILES["photo"]["size"] >= SIZE_SMALL) */
    /* 	  $scale = SCALE_SMALL; */

    /* 	$cmd = CONVERT_PROGRAM." -resize ${scale}x${scale} ".$_FILES["photo"]["tmp_name"]." ".WEB_ROOT.$rel; */
    /* 	$str = exec($cmd, $res, $rc);     */

    /* 	$this->view->assign("photo", file_exists(WEB_ROOT.$rel) ? $rel : ""); */
    /*   } */
    else
      {
	$this->view->assign("error", "请从相册选择照片。");
      }
    $this->view->assign("userid", $_REQUEST['userid']);
    $this->display();
  }
  public function update_figure()
  {
    $out_width = 100;
    $out_height = 100;
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");
    
    $this->view->assign("userid", $_REQUEST["userid"]);
    //print_r($_REQUEST);
    if (!isset($_REQUEST["x1"]) || empty($_REQUEST["x1"]) 
	||!isset($_REQUEST["y1"]) || empty($_REQUEST["y1"]) 
	||!isset($_REQUEST["x2"]) || empty($_REQUEST["x2"])
	||!isset($_REQUEST["y2"]) || empty($_REQUEST["y2"]))
      {
	die("选取坐标不完整");
      }

    $x1 = $_REQUEST['x1'];
    $x2 = $_REQUEST['x2'];
    $y1 = $_REQUEST['y1'];
    $y2 = $_REQUEST['y2'];
    $to_width = $_REQUEST['width'];
    $to_height = $_REQUEST['height'];

    $crop_width = $x2 - $x1;
    $crop_height = $y2 - $y1;
    /* if the src is a picture from the internet, do not try to build path  */
    $src = strstr($_REQUEST['photo'], "http") ? $_REQUEST['photo'] : WEB_ROOT.$_REQUEST['photo'];
    $rely = WEB_ROOT . TMP_DIR . "/".md5($src);
    $rel_dir = FIGURE_DIR."/".date("Ymd");
    $dst_dir = WEB_ROOT.$rel_dir;
    if (!is_dir($dst_dir))
      mkdir($dst_dir, 0777);
    $rel_dst = $rel_dir . "/".basename($_REQUEST["photo"]);
    $dst = $dst_dir."/".basename($_REQUEST["photo"]);
    $cmd = CONVERT_PROGRAM." -resize ${to_width} ${src} ${rely}; ";
    $cmd .= CONVERT_PROGRAM." -crop ${crop_width}x${crop_height}+${x1}+${y1} ${rely} ${rely}.1;";
    $cmd .= CONVERT_PROGRAM." -resize ${out_width}x${out_height} ${rely}.1 $dst";
    $str = exec($cmd, $res, $rc);
    M_Tools::log($cmd);

    unlink($rely);
    unlink("${rely}.1");

    if (file_exists($dst))
      {
	$this->db->edit($_REQUEST['userid'], array("figureurl"=>$rel_dst));
      }
    else
      {
	$this->view->assign("error", "抱歉，更新头像失败，请稍后重试。(cut figure error)");
      }


    $this->display();
    //die(json_encode(array("resp_id"=>"0000", "resp_data"=>array("res"=>true, "msg"=>"更新头像成功", "cmd"=>$cmd, "icon"=>$dst))));    
  }

  public function ask_delete()
  {
    $this->display();
  }

  public function delete()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $user = $this->db->delete($_REQUEST['userid']);
    $this->view->assign("user", $user);

    $this->display();
  }
  public function restore()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to edit.");

    $this->db->restore($_REQUEST['userid']);
    $this->display();
  }
  public function del_complete()
  {
    $this->display();
  }
  public function search()
  {
    $region = new M_qin_region();

    /*********************************************************************************/
    /* do search */
    if (isset($_REQUEST["realname"]) && !empty($_REQUEST["realname"]))
      {
	$table = new M_qin_users();
	$res = $table->find_users(trim($_REQUEST['realname']), isset($_REQUEST['region_code']) ? $_REQUEST['region_code'] : null);
	$this->assign("page", $table->showPages());

	$users = array();
	foreach($res as $user)
	  {	
	    $user["region_name"] = $user["region_code"] ? $region->get_full_name($user["region_code"]) : "";
	    $user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	    $users[] = $user;
	  }
	$this->view->assign("users", $users);
	$this->view->assign("realname", $_REQUEST["realname"]);
      }

    $this->view->assign("userid", (isset($_REQUEST["userid"]) && $_REQUEST["userid"]) ? $_REQUEST["userid"] : 
			(isset($_SESSION["id"]) ? $_SESSION["id"] : ""));

    /*********************************************************************************/
    /* get region date */
    $provinces = $region->getProvinceList();
    if (!isset($_REQUEST['region_code']) || empty($_REQUEST['region_code']))
      {
	$this->view->assign("provinces", M_Tools::make_options($provinces));
      }
    else
      {
	$prov_id = substr($_REQUEST['region_code'], 0, 2)."0000";
	$city_id = substr($_REQUEST['region_code'], 0, 4)."00";
	$cities = $region->getCitiesList($prov_id);
	$towns = $region->getTownsList($city_id);
	$this->view->assign("provinces", M_Tools::make_options($provinces, $prov_id));
	$this->view->assign("cities", M_Tools::make_options($cities, $city_id));
	$this->view->assign("towns", M_Tools::make_options($towns, $_REQUEST["region_code"]));
	$this->view->assign("region_code", $_REQUEST["region_code"]);
      }
    $this->display();
  }
  public function do_search()
  {
    $matches = array();
    /* if (!isset($_REQUEST['realname']) || empty($_REQUEST['realname'])) */
    /*   $this->view->assign("error", "请填写姓名！"); */

    /* if (!isset($_REQUEST['region_code']) || empty($_REQUEST['region_code'])) */
    /*   $this->view->assign("error", "请选择省份！"); */

    $table = new M_qin_users();
    $res = $table->find_users($_REQUEST['realname'], isset($_REQUEST['region_code']) ? $_REQUEST['region_code'] : null);
    $this->assign("page", $table->showPages());
    /* print_r($users); */
    $region = new M_qin_region();
    $users = array();
    foreach($res as $user)
      {	
	/* $user["age"] = (int)date("Y") - (int)substr($user["day_of_birth"], 0, 4); */
	/* print $user["region_code"]; */
	$user["region_name"] = $user["region_code"] ? $region->get_full_name($user["region_code"]) : "";
	$user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	$users[] = $user;
      }
    $this->view->assign("userid", isset($_REQUEST["userid"]) && $_REQUEST["userid"] ? $_REQUEST["userid"] : "");
    $this->view->assign("users", $users);
    $this->display();

  }
  public function detail()
  {
    if (!isset($_REQUEST['userid']) || empty($_REQUEST['userid']))
      die("You must specify a user id to show.");
    
    $table = new M_qin_users();
    $user = $table->get($_REQUEST['userid']);
    $region = new M_qin_region();
    $user["region_name"] = $user["region_code"] ? $region->get_full_name($user["region_code"]) : "";
    $user["age"] = (int)date("Y") - (int)substr($user["day_of_birth"], 0, 4);
    /* print_r($user); */
    $this->view->assign("user", $user);
    $this->display();
  }

  public function active_people()
  {
    /* $res = $this->db->orderBy("id desc")->limit(30)->fetchAll(); */
    //$visit = new M_qin_visits();
    $res = $this->db->get_hot_people();
    $users = array();
    foreach($res as $u)
      {
	$u["figure"] = M_Tools::get_figure_url($u["figureurl"], $u["gender"]);
	//$u["name"] = mb_substr($u["realname"], 0, NAME_LENGTH, 'utf-8');
	$u["name"] = function_exists("mb_substr") ? mb_substr($u["realname"], 0, NAME_LENGTH, 'utf-8') : $u["realname"];
	$users[] = $u;
      }

    /* print_r($users); */
    $this->view->assign("users", $users);
    $this->display();
  }

  public function show_photo_wall()
  {
    $this->display();
  }
  public function photo_wall()
  {
    $album = new M_qin_album();
    $photos = $album->get_some_photos();
    M_Tools::del_cache($album->LastQueryString);

    $this->view->assign("photos", $photos);

    $rand = array();
    for($i=0; $i<100; $i++)
      {
	$rand[] = rand(0,1) ? '-'.rand(0,PHOTO_MAX_ANGLE) : rand(0,PHOTO_MAX_ANGLE);
      }
    $this->view->assign("rand", $rand);
    $this->display();
  }

  public function change_photo_wall()
  {
    unlink(PHOTO_WALL_PATH);
    M_Tools::check_photo_wall();
    header("Location: /users/show_photo_wall");
  }

  public function get_latest()
  {
    $region = new M_qin_region();
    $res = $this->db->get_latest_users(10);
    $users = array();
    foreach($res as $user)
      {
	$user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	$user['region'] = $user['region_code'] ? $region->get_full_name($user['region_code']) : "";
	$users[] = $user;
      }
    $this->view->assign("users", $users);
    /* print_r($users); */
    $this->display();
  }

  public function get_more_latest()
  {
    $region = new M_qin_region();
    $res = $this->db->get_latest_users(30);
    $this->assign("page", $this->db->showPages());

    $users = array();
    foreach($res as $user)
      {
	$user["figureurl"] = M_Tools::get_figure_url($user["figureurl"], $user["gender"]);
	$user['region'] = $user['region_code'] ? $region->get_full_name($user['region_code']) : "";
	$users[] = $user;
      }
    $this->view->assign("users", $users);
    /* print_r($users); */
    $this->display();
  }
  public function open_login()
  {
	  //	print_r($_SESSION);
	  $this->display();
  }
  public function logout()
  {
    session_destroy();
    session_unset();
  }

}
//utf8编码
?>
